package Thread.Callable;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class Demo41 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //callable接口实现类的好处相对于runnable
        //1.可以返回值，省得我们再开辟一个单独的空间来接受返回值
        //2.可以抛出异常
        //3.可以获取线程执行的结果
        //4.可以指定泛型
        Callable<Integer> callable = new Callable<Integer>(){
            public Integer call() throws Exception {
                int sum=0;
                for (int i = 1; i <= 1000; i++) {
                    sum+=i;
                }
                return sum;
            }
        };
        //thread类Integer不能直接接受callable接口实现类，需要借助FutureTask类
        //futuretask相当于取餐时候的号码牌的作用
        FutureTask<Integer> futureTask = new FutureTask<>(callable);
        Thread t = new Thread(futureTask);
        t.start();
        //get方法会阻塞，直到线程执行完毕，获取到返回值
        System.out.println("sum ="+futureTask.get());
    }
}
